package doubleCS.dataService;
import java.sql.*;

/**
 * @author fengke
 */
public class ConnectMySql {
    Connection connect = null;
    Statement sta = null;
    /**
     * 接收数据库遍历返回值
     */
    ResultSet res = null;

    /**
     * 连接MySql
     * @return
     */
    public Connection openMySql(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/mySql?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            String users = "root";
            String password = "754709489@qq.com";
            this.connect = DriverManager.getConnection(url,users,password);
            System.out.println("Success Connect To MySql!");
//            System.out.println(connect);
        }catch(Exception e){

        }
        return connect;
    }

    /**
     * 增删改
     * @param sql
     * @return
     */
    public int update(String sql){
        int result = 0;
        try {
            sta = connect.createStatement();
            result = sta.executeUpdate(sql);
            System.out.println(result);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    /**
     * select
     * @param sql
     * @return
     */
    public ResultSet select(String sql){
        try{
            sta = connect.createStatement();
            res = sta.executeQuery(sql);
        }catch(Exception e){}
        return res;
    }

    /**
     * 高频查询数据库可以在查询后关闭数据库连接
     */
    public void closeMySql(){
        try {  //防止空指针异常
            res.close();
            sta.close();
            connect.close();
        }catch (Exception e){}

    }

    /**
     * 查询数据库结构
     * @param tableName
     */
    public void showTableMataData(String tableName){
        try {
            ConnectMySql con = new ConnectMySql();
            con.openMySql();
            ResultSet re = con.select("Select * From "+tableName+"");
            //获取标源数据
            ResultSetMetaData mata = re.getMetaData();
            //得到列数
            int sum = mata.getColumnCount();
            for(int i =1 ; i<=sum ; i++){
                System.out.println(mata.getColumnName(i)+"-"+mata.getColumnType(i)+"-"+mata.getColumnTypeName(i));
            }
        }catch(Exception e){}
    }
}
